# -*- codeing = utf-8 -*-

from django.shortcuts import redirect, render, HttpResponse
from django.http import JsonResponse
from django.db.models import Q

from user import models
from user.forms import account


def user_login(request):
    """用户账号密码登录"""
    forms_obj = account.UserLoginForm(request)
    if request.method == 'POST':
        print(request.POST)
        forms_obj = account.UserLoginForm(request, request.POST)
        bak_dic = {'status': True, 'msg': ''}
        if forms_obj.is_valid():
            username = forms_obj.cleaned_data.get('username')
            password = forms_obj.cleaned_data.get('password')
            user_obj = models.UserInfo.objects.filter(
                Q(username=username) | Q(email=username) | Q(phone=username)).filter(password=password).first()
            if user_obj:
                # 用户名密码正确
                request.session['user_id'] = user_obj.id
                request.session.set_expiry(60 * 60 * 24 * 14)
            else:
                bak_dic['status'] = False
                forms_obj.add_error('password', '用户名或密码错误')
                bak_dic['msg'] = forms_obj.errors
        else:
            bak_dic['status'] = False
            bak_dic['msg'] = forms_obj.errors
        return JsonResponse(bak_dic, safe=True)
    return render(request, 'user/user_login.html', locals())

def logout(request):
    del request.session['user_id']
    return redirect('user:user_login')












